package cn.hm.controller;

import cn.hm.domain.User;
import cn.hm.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/user",produces = "application/json;charset=utf-8")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list.do")
    public ModelAndView list(ModelAndView mv){
        List<User> users = userService.selectAll();
        mv.addObject("users", users);
        mv.setViewName("home");
        return mv;
    }

    /**
     * 登录
     * @param response
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login.do")
    @ResponseBody
    public Map<String, Object> login(HttpServletResponse response, String username, String password){
        User user = userService.login(username, password);
        System.out.println("user = " + user);
        Map<String, Object> map = new HashMap<>();
        if (user == null) {
            map.put("msg", "对不起，用户名和密码不正确");
            return map;
        }
        map.put(user.getUid(), user);
        return map;
    }

    /**
     * 添加用户
     * @param user
     * @return yanggang
     */
    @PostMapping("/register.do")
    public String register(User user){
        Integer count = userService.save(user);
        if (count == 0){
            throw new RuntimeException("添加失败！");
        } else if (count == 1){
            System.out.println("添加成功！");
        }
        return "redirect:/user/list.do";
    }

    @GetMapping("/update.do")
    public String updateUser(User user){
        Integer count = userService.update(user);
        return "redirect:/user/list.do";
    }

    /**
     * 访问WEB-INF中间方法
     * @return yanggang
     */
    @GetMapping("/regist.do")
    public ModelAndView goRegister(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("regist");
        return mv;
    }

    /**
     * 访问WEB-INF中间方法
     * @return yanggang
     */
    @GetMapping("/goUpdate.do")
    public ModelAndView goUpdate(String uid){
        User user = userService.selectById(uid);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("update");
        mv.addObject(user);
        return mv;
    }

    /**
     * 删除用户
     * @param uid
     * @return
     */
    @GetMapping("/delete.do")
    public String delete(@Param("ids") Integer[] ids){
        for (Integer id : ids) {
            System.out.println("ids = " + id);
        }
        int count = userService.delete(ids);
        System.out.println("count = " + count);
        return "redirect:/user/list.do";
    }

}
